package com.dreamlin.basepro.base.viewmodel;

import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;


public class BaseViewModel extends ViewModel {

    private CompositeDisposable compositeDisposable;

    private MutableLiveData<LoadingModel> loadingModel;

    private MutableLiveData<String> errorModel;

    public BaseViewModel() {
        compositeDisposable = new CompositeDisposable();
        loadingModel = new MutableLiveData<>();
        errorModel = new MutableLiveData<>();
    }

    public void initDialog(LifecycleOwner owner, Observer<LoadingModel> observer) {
        loadingModel.observe(owner, observer);
    }

    public void initError(LifecycleOwner owner, Observer<String> observer) {
        errorModel.observe(owner, observer);
    }

    public void setLoading(LoadingModel model) {
        loadingModel.setValue(model);
    }

    public void setError(String error) {
        errorModel.setValue(error);
    }

    protected void addDisposable(Disposable disposable) {
        compositeDisposable.add(disposable);
    }

    @Override
    protected void onCleared() {
        if (compositeDisposable != null && compositeDisposable.size() > 0
                && !compositeDisposable.isDisposed()) {
            compositeDisposable.dispose();
        }
        super.onCleared();
    }
}
